// createRouter              创建路由实例的函数
// createWebHashHistory      创建哈希Hash路由函数(推荐)
// createWebHistory          创建History路由函数
import { createRouter, createWebHashHistory } from 'vue-router'

import TopCategory from '@/views/category/index.vue'
import SubCategory from '@/views/category/sub.vue'

const Layout = () => import('@/views/Layout')
const Home = () => import('@/views/home/index')
// 路由：路径和组件映射关系
const routes = [
  {
    path: '/',
    component: Layout,
    children: [
      { path: '/', component: Home },
      { path: 'category/:id', component: TopCategory },
      { path: 'category/sub/:id', component: SubCategory },
      { path: 'product/:id', component: () => import('@/views/goods/index.vue') },
      { path: 'cart', component: () => import('@/views/cart/index.vue') }
    ]
  },
  { path: '/login', component: () => import('@/views/login/index.vue') },
  { path: '/login/callback', component: () => import('@/views/login/callback.vue') }

]

// 创建路由实例
const router = createRouter({
  // 哈希路由
  history: createWebHashHistory(),
  // 路由映射配置
  routes,
  // 滚动行为 https://next.router.vuejs.org/zh/guide/advanced/scroll-behavior.html
  scrollBehavior (to, from, savedPosition) {
  // 如果是首页
    if (to.path === '/') {
    // 保留原来的位置
      return savedPosition
    } else {
      // 其他页面，始终滚动到顶部
      // 💥 vue2的配置和Vue3有差别：x 改名为 left，y 改名为 top
      return { top: 0, behavior: 'smooth' }
    }
  }
})

// 导出路由实例
export default router
